package com.example.demo.config;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/8/2
 * \* Time: 16:51
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义用户登录的拦截器
 */
@Component
public class LoginIntercept implements HandlerInterceptor {

    /**
     * 返回true表示拦截判断通过，可以访问后面的接口，反之则不可
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //1.得到HttpSession对象
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("userinfo") != null){
            //表示已经登录
            return true;
        }
        //执行到此，表示未登录，未登录就跳转到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}
